//
//  Tools.m
//  POS
//
//  Created by 廉英雷 on 15/9/24.
//  Copyright © 2015年 廉英雷. All rights reserved.
//

#import "Tools.h"
#import "Reachability.h"
#import "UIDevice-Reachability.h"
#import "loadView.h"
#import "MBProgressHUD.h"
#define  _height  [[UIScreen mainScreen] bounds].size.height

#define  _width   [[UIScreen mainScreen] bounds].size.width
@class MBProgressHUD;
@interface Tools ()

@property(nonatomic,strong)loadView * myLoadView;

@property (nonatomic, strong) MBProgressHUD  *hud;
@end

@implementation Tools

+(instancetype)shareTools;
{
      static Tools * tool;
      static dispatch_once_t tocken;
      dispatch_once(&tocken, ^{
            tool=[[Tools alloc]init];
      });
      return tool;
}



+(NSString *)getUUID;
{
      NSUUID * uuid=[[UIDevice currentDevice] identifierForVendor];
      return [uuid UUIDString];
}
+(NSString *)getVersion
{
      NSString * version=[[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
      return version;
}

//8.7 添加提示信息，几秒钟后自动消失
- (void)showAlertWithText:(NSString *)text
{
      UIFont * font =[UIFont systemFontOfSize:14];
      
      UILabel * label=[[UILabel alloc] init];
      // label.backgroundColor=[UIColor colorWithWhite:0.377 alpha:0.300];
      label.backgroundColor = [UIColor blackColor];
      label.text=text;
      label.textAlignment=NSTextAlignmentCenter;
      label.font=font;
      label.layer.cornerRadius=10;
      label.clipsToBounds=YES;
      label.alpha=0;
      label.textColor = [UIColor whiteColor];
     
      label.frame = CGRectMake(0, 0, [text sizeWithAttributes:@{NSFontAttributeName:font}].width+60, 40);
      label.center=CGPointMake(_width*0.5, _height*0.4);  
      
      UIWindow * window=[[UIApplication sharedApplication] keyWindow];
      [window addSubview:label];
      
      
      [UIView animateWithDuration:0.5 animations:^{
            label.alpha=1;
      } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:2.0 delay:0.5 options:UIViewAnimationOptionCurveLinear animations:^{
                  label.alpha=0;
            } completion:^(BOOL finished) {
                  [label removeFromSuperview];
            }];
            
      }];
}

+ (BOOL) allNumber:(NSString *) text
{
      NSString* regex = @"^\\+?[1-9][0-9]*$";
      NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
      return [pred evaluateWithObject:text];
}

+(BOOL)isPassword:(NSString*)text{//密码由6--16位字母和数字组成
      NSString* regex = @"^[[0-9]|[a-z,A-Z]]{8,18}$";
      NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
      
      if ([pred evaluateWithObject:text])
      {
            if ([self allNumber:text]) {
                  return NO;
            }
            if ([text rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]].location==NSNotFound) {
                  return NO;
            }
            return YES;
            
      }
      return NO;
      
}
+(BOOL)stringIsMobile:(NSString *)mobil;
{
      //手机号以13， 15，18开头，八个 \d 数字字符
      NSString *phoneRegex = @"^(1）\\d{10}$";
      NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
      return [phoneTest evaluateWithObject:mobil];
}

+(BOOL)isEmail:(NSString*)text{
      //    NSString* regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
      NSString* regex = @"^[0-9a-z_][-_\\.0-9a-z-]{0,63}@([0-9a-z][0-9a-z-]*\\.)+[a-z]{2,4}$";
      NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
      return [pred evaluateWithObject:text];
}

#pragma mark----httpHeader


+(NSDictionary *)checkHttpHeader;
{
      NSDictionary * dict=@{@"Accept": [NSString stringWithFormat:@"application/vnd.ehking.kaptcha-v%@+json",[Tools getVersion]],
                            @"Content-type": [NSString stringWithFormat:@"application/vnd.ehking.kaptcha-v%@+json",[Tools getVersion]], //POST/PUT提交必选
                            @"User-Agent":[NSString stringWithFormat:@"IOS-Pos-v%@",[Tools getVersion]]};
      return dict;
}

+(NSDictionary *)vipHttpHeader;
{
      NSDictionary * dict=@{@"Accept": [NSString stringWithFormat:@"application/vnd.ehking.member-v%@+json",[Tools getVersion]],
                            @"Content-type": [NSString stringWithFormat:@"application/vnd.ehking.member-v%@+json",[Tools getVersion]], //POST/PUT提交必选
                            @"User-Agent":[NSString stringWithFormat:@"IOS-Pos-v%@",[Tools getVersion]]};
      return dict;
}

+(NSDictionary *)LoginHttpHeader{

      NSDictionary * dict=@{@"Accept": [NSString stringWithFormat:@"application/vnd.ehking.cas-v%@+json",[Tools getVersion]],
                            @"Content-type": [NSString stringWithFormat:@"application/vnd.ehking.cas-v%@+json",[Tools getVersion]], //POST/PUT提交必选
                            @"User-Agent":[NSString stringWithFormat:@"IOS-Pos-v%@",[Tools getVersion]]};
      return dict;


}
#pragma mark-----
-(void)startLoadingWithText:(NSString *)text;
{
      
      if (![UIDevice networkAvailable])
      {
            
            [[Tools shareTools] alert:@"网络请求失败" :@"请检查手机网络设置."];
            
            return;//如果没网，不出现加载框
            //        [[Tools shareTools] stopLoading];
      }
      
      
      if (!self.myLoadView) {
            self.myLoadView=[[loadView alloc]initWithFrame:CGRectMake(0, 0, _width, _height)];
      }
      
      self.myLoadView.frame=CGRectMake(0, 0, _width, _height);
      UIWindow * window=[[UIApplication sharedApplication] keyWindow];
      [window addSubview:self.myLoadView];
      [self.myLoadView startLoadWithTitle:text];
}
-(void)stopLoading;
{
      [self.myLoadView stopLoading];
      self.myLoadView.frame=CGRectMake(0, _height, _width, _height);
      
}

+ (char *)UTF8_To_GB2312:(NSString*)utf8string
{
      NSStringEncoding encoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
      const char *gb2312 = [utf8string cStringUsingEncoding:encoding];
      return gb2312;
}

-(void)showHUD:(NSString *)title afterTime:(double)seconds failStr:(NSString *)str{
      
   //   self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = title;
      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            
            if (_hud) {
                  [_hud hide:YES];
                  _hud = nil;
                  [self showTipView:str];
            }
      });
      
      
}

- (void)showHUDDelayHid:(NSString *)title {
    //  self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = title;
      
      [self performSelector:@selector(hideHUD) withObject:nil afterDelay:1];
}

//隐藏加载
- (void)hideHUD {
      if (_hud) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                  [_hud hide:YES];
                  _hud = nil;
            });
      }
      
      //[self.hud hide:YES];
      
}

//隐藏加载显示加载完成提示
- (void)hideHUDWithTitle:(NSString *)title
{
      self.hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
      
      self.hud.mode = MBProgressHUDModeCustomView;
      
      self.hud.labelText = title;
      [self.hud hide:YES afterDelay:1];
      
}




@end
